import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Widget/MyBgPage.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';

class TeachMaterialManagerFiles extends StatefulWidget {
  String materialCode;

  TeachMaterialManagerFiles(this.materialCode);

  @override
  State<StatefulWidget> createState() {
    return _TeachMaterialManagerFiles();
  }
}

class _TeachMaterialManagerFiles extends State<TeachMaterialManagerFiles> {
  delFile(int index) {
    showBtn2Dialog(context, "您確定要刪除此檔案嗎?", "取消", () {}, "刪除", () {
      HttpGo(context).post("/Material/DeleteOwnMaterialFile", {"materialFileId": files[index]["ownerMaterialFileId"]}, (data) {
        showToast("刪除成功");
        files.removeAt(index);
        setState(() {});
      }, (code, error) => showToast(error));
    });
  }

  List<dynamic> files = [];

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getFiles();
    });
    super.initState();
  }

  getFiles() {
    HttpGo(context).get("/Material/GetOwnMaterialFiles?materialCode=${widget.materialCode}", {}, (data) {
      files = data["materials"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  adjustList() {
    List<int> list = [];
    for (var item in files) {
      list.add(item["ownerMaterialFileId"]);
    }
    HttpGo(context).post("/Material/SortOwnMaterialFile", {"materialCode": widget.materialCode, "ownerMaterialFileIdList": list}, (data) {
      showToast("更新成功");
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return MyBgPage(
        "",
        Container(
            margin: EdgeInsets.fromLTRB(16, 16, 16, 24),
            decoration: Global.getWhiteBg_shadow(8, MyColor.DD),
            child: Column(children: [
              Padding(
                  padding: EdgeInsets.fromLTRB(16, 16, 16, 0),
                  child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                    LocalImage("file.png", height: 24, width: 32),
                    Text("Files", style: TextStyle(fontSize: 15, color: MyColor.Orange, fontWeight: FontWeight.bold))
                  ])),
              Container(height: 0.5, color: MyColor.Orange, margin: EdgeInsets.only(top: 6, bottom: 16)),
              Expanded(
                  child: ReorderableListView.builder(
                      itemBuilder: (BuildContext context, int index) {
                        return ItemFile(files[index], key: ValueKey(index), onDelTap: () {
                          delFile(index);
                        });
                      },
                      onReorder: (int oldIndex, int newIndex) {
                        // 如果是往下移，新位置需要-1；因為會先把舊的remove，所以舊item後面的index長度會-1；
                        // 往上移則無影響，因為刪除舊Item只會影響舊Item後面的Item
                        if (oldIndex < newIndex) {
                          newIndex -= 1;
                        }
                        var child = files.removeAt(oldIndex);
                        files.insert(newIndex, child);
                        setState(() {});
                        adjustList();
                      },
                      itemCount: files.length))
            ])));
  }
}

class ItemFile extends StatelessWidget {
  dynamic file;
  Function()? onDelTap;

  ItemFile(this.file, {Key? key, this.onDelTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String date = getStrTime(getTimeByUtc(file["createDateTime"]), DateUtil.YMD);
    if (file["fileSize"].toString().length > 4) file["fileSize"] = file["fileSize"].toString().substring(0, 4);

    return Container(
        decoration: Global.getBg(Color(0xffe2f2f2), 8),
        padding: EdgeInsets.all(8),
        margin: EdgeInsets.symmetric(vertical: 4, horizontal: 16),
        child: Row(children: [
          LocalImage("file_g.png", width: 22, height: 22),
          Container(width: 12),
          Expanded(
              child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text("${file["fileName"]}", style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: MyColor.Green)),
            Text("$date / ${file["fileSize"]}MB", style: TextStyle(fontSize: 12, height: 2, color: MyColor.C7D))
          ])),
          LocalImage("delete.png", width: 24, onTap: onDelTap)
        ]));
  }
}
